package com.dragon.flow.rest.api;


import com.dragon.flow.model.leave.Screening;
import com.dragon.flow.service.flowable.IFlowableProcessInstanceService;
import com.dragon.flow.service.flowable.IFlowableTaskService;
import com.dragon.flow.service.leave.IScreeningService;
import com.dragon.flow.vo.flowable.CompleteTaskVo;
import com.dragon.flow.vo.flowable.StartProcessInstanceVo;
import com.dragon.tools.common.ReturnCode;
import com.dragon.tools.common.UUIDGenerator;
import com.dragon.tools.pager.PagerModel;
import com.dragon.tools.pager.Query;
import com.dragon.tools.vo.ReturnVo;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.idm.api.User;
import org.flowable.ui.common.security.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * description : 筛查Controller
 */
@RestController
@RequestMapping("/rest/demo/screening")
public class ScreeningController extends BaseResource {
    private static Logger logger = LoggerFactory.getLogger(ScreeningController.class);

    @Autowired
    private IScreeningService screeningService;
    @Autowired
    private IFlowableProcessInstanceService flowableProcessInstanceService;
    @Autowired
    private IFlowableTaskService flowableTaskService;

    @GetMapping("/list")
    public PagerModel<Screening> list(Screening screening, Query query) {
        PagerModel<Screening> pm = null;
        try {
            pm = screeningService.getPagerModelByQuery(screening, query);
        } catch (Exception e) {
            logger.error("ScreeningController-ajaxList:", e);
            e.printStackTrace();
        }
        return pm;
    }

    //添加
    @PostMapping("/add")
    public ReturnVo add(Screening screening, String sessionId) {
        ReturnVo returnVo = new ReturnVo(ReturnCode.FAIL, "添加失败");
        try {
            String screeningId = UUIDGenerator.generate();
            screening.setId(screeningId);
            StartProcessInstanceVo startProcessInstanceVo = new StartProcessInstanceVo();
            startProcessInstanceVo.setBusinessKey(screeningId);
            User user = SecurityUtils.getCurrentUserObject();
            startProcessInstanceVo.setCreator(user.getId());
            startProcessInstanceVo.setCurrentUserCode(user.getId());
            startProcessInstanceVo.setFormName("筛查流程");
            startProcessInstanceVo.setSystemSn("flow");
            startProcessInstanceVo.setProcessDefinitionKey("screening");
            Map<String, Object> variables = new HashMap<>();
            // variables.put("degree", screening.getDegree());
            startProcessInstanceVo.setVariables(variables);
            ReturnVo<ProcessInstance> returnStart = flowableProcessInstanceService.startProcessInstanceByKey(startProcessInstanceVo);
            if (returnStart.getCode().equals(ReturnCode.SUCCESS)){
                String processInstanceId = returnStart.getData().getProcessInstanceId();
                screening.setProcessInstanceId(processInstanceId);
                screeningService.insertScreening(screening);
                returnVo = new ReturnVo(ReturnCode.SUCCESS, "添加成功");
            }else {
                returnVo = new ReturnVo(returnStart.getCode(), returnStart.getMsg());
            }
        }catch (Exception e){
            logger.error("ScreeningController-add:", e);
            e.printStackTrace();
        }

        return returnVo;
    }

    //修改
    @PostMapping("/update")
    public ReturnVo update(Screening screening) {
        ReturnVo returnVo = new ReturnVo(ReturnCode.FAIL, "修改失败");
        try {
            screeningService.updateScreening(screening);
            returnVo = new ReturnVo(ReturnCode.SUCCESS, "修改成功");
        } catch (Exception e) {
            logger.error("ScreeningController-update:", e);
            e.printStackTrace();
        }
        return returnVo;
    }

    //删除
    @GetMapping("/dels")
    public ReturnVo dels(String[] ids) {
        ReturnVo returnVo = new ReturnVo(ReturnCode.FAIL, "删除失败");
        try {
            for(String id: ids) {
                screeningService.delScreeningById(id);
            }
            returnVo = new ReturnVo(ReturnCode.SUCCESS, "删除成功");
        } catch (Exception e) {
            logger.error("ScreeningController-del:", e);
            e.printStackTrace();
        }
        return returnVo;
    }

    /**
     * 审批任务
     *
     * @param params 参数
     * @return
     */
    @PostMapping(value = "/complete")
    public ReturnVo<String> complete(@RequestBody CompleteTaskVo params) {
        boolean flag = this.isSuspended(params.getProcessInstanceId());
        ReturnVo<String> returnVo = null;
        if (flag){
            params.setUserCode(this.getLoginUser().getId());
            returnVo = flowableTaskService.complete(params);
        }else{
            returnVo = new ReturnVo<>(ReturnCode.FAIL,"流程已挂起，请联系管理员激活!");
        }
        return returnVo;
    }
}
